<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="mini" inline style="white-space: nowrap; overflow-x: auto">
      <el-form-item>
        <el-date-picker v-model="yearMonth" type="month" placeholder="选择月份" value-format="yyyy-MM" :clearable="false" @change="changeYearMonth" style="width: 110px" />
      </el-form-item>
      <el-form-item prop="countLevel">
        <el-select v-model="queryParams.countLevel" placeholder="统计级别" clearable style="width: 120px">
          <el-option v-for="dict in countLevels" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input placeholder="输入内容" v-model.trim="toggleInput" clearable @keyup.enter.native="handleQuery">
          <el-select v-model="toggleSelect" slot="prepend" style="width: 100px">
            <el-option label="项目名称" value="projectName" />
            <el-option label="集群" value="oneLevelOrgName" />
            <el-option label="事业部" value="twoLevelOrgName" />
            <el-option label="城市公司" value="threeLevelOrgName" />
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item :class="{ disabled: disableAction }">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-dropdown @command="onExportType" :disabled="exportLoading">
          <el-button icon="el-icon-download" :loading="exportLoading" style="margin-left: 10px">导出</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="1">工程得分情况表</el-dropdown-item>
            <el-dropdown-item command="2">工程得分详情表</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button @click="$refs.SelectFields.open(dt_selected)" style="margin-left: 10px">选择展示字段</el-button>
      </el-form-item>
    </el-form>

    <el-table :key="dt_tableKey" v-loading="listLoading" :data="list" size="small" height="calc(100vh - 150px)">
      <template v-for="i in dt_cols">
        <el-table-column v-if="jtjqFields.includes(i.value)" :label="i.label" :key="i.value" align="center">
          <el-table-column label="检查数量" :prop="`${i.value}.ciNum`" :key="`${i.value}.ciNum`" align="center" />
          <el-table-column label="合格数量" :prop="`${i.value}.valNum`" :key="`${i.value}.valNum`" align="center" />
          <el-table-column label="优秀数量" :prop="`${i.value}.excNum`" :key="`${i.value}.excNum`" align="center" />
          <el-table-column label="合格率" :prop="`${i.value}.valRate`" :key="`${i.value}.valRate`" align="center" />
          <el-table-column label="优秀率" :prop="`${i.value}.excRate`" :key="`${i.value}.excRate`" align="center" />
        </el-table-column>
        <el-table-column v-else v-bind="i" :prop="i.value" :key="i.value" />
      </template>
    </el-table>

    <SelectFields ref="SelectFields" @selected="onSelectFields" />
  </div>
</template>
<script>
// 工程得分情况
import { gatherEngineerScore, exportEngineerScore } from '@/api/statement/trdQc'
import { jtFieldList, jqFieldList, fieldList, countLevels } from './trdQcEngineerScore/fieldList'
import SelectFields from './trdQcEngineerScore/SelectFields'
// 集团/集群的特殊字段，一个字段对应5列
const jtjqFields = [...jtFieldList, ...jqFieldList].map(i => i.value)

export default {
  name: 'TrdQcEngineerScore',
  components: { SelectFields },
  data() {
    const firstDay = new Date().Format('yyyy/MM/01 00:00:00')
    const lastMonth = new Date(new Date(firstDay) - 1).Format('yyyy-MM')
    return {
      jtjqFields,
      countLevels,
      // Dynamic thead - columns options
      dt_selected: ['oneLevelOrgName', 'twoLevelOrgName', 'threeLevelOrgName', 'projectName', 'jtGcScore', 'weightJt', 'jqGcScore', 'weightJq', 'sybScore', 'weightSyb', 'gcScore'],
      dt_cols: [],
      dt_tableKey: 1,

      listLoading: false,
      list: [],
      queryParams: { countLevel: '' },
      yearMonth: lastMonth,
      toggleSelect: 'projectName',
      toggleInput: '',
      exportType: 1,
      exportLoading: false
    }
  },
  computed: {
    disableAction() {
      return this.listLoading || this.exportLoading
    }
  },
  created() {
    this.handleDtSelected()
    this.getList()
  },
  methods: {
    async getList() {
      const { yearMonth, toggleSelect, toggleInput } = this
      if (!yearMonth) return this.msgInfo('请选择月份')

      const opt = { ...this.queryParams }
      const yMonth = yearMonth.split('-')
      opt.countYear = yMonth[0]
      opt.countMonth = yMonth[1]
      toggleSelect && toggleInput && (opt[toggleSelect] = toggleInput)

      this.listLoading = true
      const res = await gatherEngineerScore(opt).catch(() => false)
      this.listLoading = false
      if (res === false) return

      const data = res.data || []
      data.map(i => {
        // 字段值保留两位小数
        Object.keys(i).map(k => {
          if (k === 'numMap' || k === 'scoreMap') return
          // if (!k.endsWith('Num') && !k.endsWith('Rate') && !k.endsWith('Score') && !k.startsWith('weight')) return
          const val = i[k]
          if (!val || isNaN(+val)) return
          let newVal = (+val).toFixed(2)
          // 权重加 %
          if (k.includes('weight')) newVal += '%'
          i[k] = newVal
        })

        // 将 numMap 的字段解构到当前 item，值保留两位小数
        const numData = i.numMap || {}
        const defaultVal = { ciNum: null, valNum: null, excNum: null, valRate: null, excRate: null }
        jtjqFields.map(field => {
          const obj = numData[field] || { ...defaultVal }
          Object.keys(obj).map(k => {
            // 数量不处理
            if (k.includes('Num')) return
            const val = obj[k]
            if (!val || isNaN(+val)) return
            obj[k] = (+val).toFixed(2)
          })
          i[field] = obj
        })

        // 将 scoreMap 的字段解构到当前 item，值保留两位小数
        const scoreData = i.scoreMap
        if (!scoreData) return
        Object.keys(scoreData).map(k => {
          const val = scoreData[k]?.score
          if (!val || isNaN(+val)) return (i[k] = val)
          i[k] = (+val).toFixed(2)
        })
      })
      this.list = data
    },
    handleQuery() {
      this.getList()
    },
    changeYearMonth(val) {
      if (!val) return
      this.getList()
    },
    handleDtSelected() {
      const keys = this.dt_selected
      this.dt_cols = keys.length ? fieldList.filter(i => keys.includes(i.value)) : fieldList
      this.dt_tableKey++
    },
    onSelectFields(selected) {
      this.dt_selected = selected
      this.handleDtSelected()
    },
    onExportType(command) {
      this.exportType = +command || 1
      this.handleExport()
    },
    async handleExport() {
      const { yearMonth, toggleSelect, toggleInput, exportType } = this
      if (!yearMonth) return this.msgInfo('请选择月份')
      if (!this.list.length) return this.msgInfo('暂无数据')

      const filename = exportType === 2 ? '工程得分详情表' : '工程得分情况表'
      const opt = { ...this.queryParams, exportType }
      const yMonth = yearMonth.split('-')
      opt.countYear = yMonth[0]
      opt.countMonth = yMonth[1]
      toggleSelect && toggleInput && (opt[toggleSelect] = toggleInput)

      const res1 = await this.$confirm(`确定导出${filename}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      this.exportLoading = true
      const res = await exportEngineerScore(opt).catch(() => false)
      this.exportLoading = false
      if (res === false) return

      const elink = document.createElement('a')
      elink.download = `${filename}_${yearMonth}.xlsx`
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(new Blob([res]))
      elink.click()
    }
  }
}
</script>
